package com.atguigu.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * @DefaultProperties注解用来配置默认的服务降级所对应的兜底方法
 */
@Service
@DefaultProperties(defaultFallback = "returnError")
public class PaymentService {

    //成功
    @HystrixCommand
    public String paymentInfo_OK(Integer id){
        return "线程池："+Thread.currentThread().getName()+"   paymentInfo_OK,id：  "+id+"\t"+"哈哈哈"  ;
    }

    //失败

    /**
     * 服务降级,当服务发生超时,报错,宕机时
     * 开启服务降级(服务降级通常部署在客户端,但是服务器端以及客户端均可以部署)
     * @param id
     * @return
     * 当服务发生超时,报错,宕机时
     * 将服务交由其它处理
     */
    /*服务的响应时间的上限为5S*/
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    })
    public String paymentInfo_TimeOut(Integer id){
        int timeNumber = 3;
        try { TimeUnit.SECONDS.sleep(timeNumber); }catch (Exception e) {e.printStackTrace();}
        return "线程池："+Thread.currentThread().getName()+"   paymentInfo_TimeOut,id：  "+id+"\t"+"呜呜呜"+" 耗时(秒)"+timeNumber;
    }

    public String returnError(){
        return "服务器发生超时|报错|宕机";
    }

    /*服务熔断*/

    /**
     * 开启服务熔断,当在10S的时间窗口期内
     * 有十次请求,失败的几率达到百分之六十,那么便开启熔断(没达到十次的量,则一定不会熔断,失败的会进行服务的降级)
     * 当熔断之后,在熔断的计时器以内,正常的请求也不会响应,而是直接服务降级,
     * 当熔断的计时器到达预定时间以后,那么熔断器会处于半开的状态,
     * 如果下一次请求失败,那么熔断器会再次断开
     * 如果下一次请求成功,则会闭合熔断器,正常接收请求
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),  //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),   //请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),  //时间范围
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"), //失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id){
        if (id < 0){
            throw new RuntimeException("*****id 不能负数");
        }
        String serialNumber = IdUtil.simpleUUID();

        return Thread.currentThread().getName()+"\t"+"调用成功,流水号："+serialNumber;
    }


    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
        return "id 不能负数，请稍候再试,(┬＿┬)/~~     id: " +id;
    }


}

